﻿using System;
using System.Runtime.InteropServices;

namespace BMproductions.Media.MediaPlayer.WMPPlus {
	public abstract class WMPMenuItem: IDisposable {
		IntPtr native;

		public WMPMenu Owner { get; private set; }
		public abstract string Text { get; }

		protected internal virtual void Invoke(IntPtr hWnd) { }

		[DllImport(WMPPlusPublic.WMPPlusHookName, CharSet = CharSet.Auto, EntryPoint = "#501")]
		private static extern IntPtr CreateMenuItem(IntPtr menu,
			[MarshalAs(UnmanagedType.LPTStr)] string text);
		[DllImport(WMPPlusPublic.WMPPlusHookName, EntryPoint = "#502")]
		private static extern void DestroyMenuItem(IntPtr item);
		[DllImport(WMPPlusPublic.WMPPlusHookName, EntryPoint = "#505")]
		private static extern bool InsertMenuItem(IntPtr item, IntPtr hMenu, int pos);

		public WMPMenuItem(WMPMenu owner) : this(owner, true) { }
		protected WMPMenuItem(WMPMenu owner, bool prepare) {
			Owner = owner;
			if (prepare)
				Init();
		}

		protected virtual void Init() {
			if (Owner != null) {
				this.native = CreateMenuItem(Owner.Native, Text);
				Owner.Items.Add(this.native, this);
			}
		}

		public void Dispose() {
			if (this.native != IntPtr.Zero && Owner != null) {
				Owner.Items.Remove(this.native);
				DestroyMenuItem(this.native);
			}
			this.native = IntPtr.Zero;
		}

		public bool Insert(IntPtr hMenu, int pos) {
			return InsertMenuItem(this.native, hMenu, pos);
		}
	}
}
